package com.michau.testitas.common.util.model.image;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * User: michau
 * Date: 3/30/13
 * Time: 4:27 PM
 */
public class ImageUtil {

    private static Log log = LogFactory.getLog(ImageUtil.class);

    public static byte[] loadImage(String path, String format){
        byte[] imageArray = null;
        Path imagePath = Paths.get(path);
        BufferedImage img = null;
        if (Files.exists(imagePath)){
            try{
                img = ImageIO.read(imagePath.toFile());
                imageArray = bufferedImageToByteArray(img, format);
            } catch (IOException ex){
                log.error("There has been a problem with reading from image file: " + imagePath.toString());
            }
        } else {
            log.warn("Cannot load image file: " + imagePath.toString());
        }
        return imageArray;
    }

    public static void saveImage(String path, BufferedImage image, String format, boolean createFile){
        if (image == null){
            throw new IllegalArgumentException("Saved file cannot be null!");
        }
        Path imagePath = Paths.get(path);
        if (createFile && !Files.exists(imagePath)) {
            try {
                Files.createFile(imagePath);
            } catch (IOException ex) {
                log.error("There has been a problem with creating file at: " + imagePath.toString());
            }
        }
        if (Files.exists(imagePath)) {
            try{
                ImageIO.write(image, format, imagePath.toFile());
            } catch (IOException ex){
                log.error("There has been a problem with writing to image file: " + imagePath.toString());
            }
        } else {
            log.error("No file found at: " + imagePath.toString());
        }
    }

    public static byte[] bufferedImageToByteArray(BufferedImage image, String format) throws IOException{
        byte imageArray[] = null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, format, baos );
        baos.flush();
        imageArray = baos.toByteArray();
        baos.close();
        return imageArray;
    }

    public static BufferedImage byteArrayToBufferedImage(byte[] imageArray) throws IOException{
        BufferedImage image = null;
        InputStream in = new ByteArrayInputStream(imageArray);
        image = ImageIO.read(in);
        return image;
    }

}
